package com.cheng.chengrobot.handler.messageForwardHandler;

import com.cheng.chengrobot.domain.MessageForward;
import com.cheng.chengrobot.service.MessageForwardService;
import com.cheng.chengrobot.service.RobotService;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.FriendMessageEvent;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.PlainText;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class FriendMessageForwarder
        extends SimpleListenerHost
{

    @Autowired
    MessageForwardService messageForwardService;

    @Autowired
    RobotService robotService;

    @EventHandler
    public void frowardFriendMessage(@NotNull FriendMessageEvent event) throws Exception { // 可以抛出任何异常, 将在 handleException 处理
        Long robotQq = event.getBot().getId();
        Long senderQq = event.getSender().getId();

        //判断来消息的机器人是否开启消息转发
        if (!robotService.isForwardTurnedOn(robotQq))
        {
            return;
        }

        List<MessageForward> messageForwardList = messageForwardService.getMessageForward(robotQq, senderQq, null,
                                                                                          null);

        //循环发送
        for (MessageForward messageForward : messageForwardList)
        {
            //如果送消息的机器人没开转发就不转发
            if (!robotService.isForwardTurnedOn(messageForward.getToRobotQq()))
            {
                continue;
            }

            Bot toRobot = Bot.getInstance(messageForward.getToRobotQq());
            //如果设置了转发到群就转发到那个群，设置了转发到好友就转发到好友
            if (messageForward.getToGroup() != null)
            {
                //在消息链前面添加fix
                MessageChain chain = event.getMessage();
                toRobot.getGroup(messageForward.getToGroup()).sendMessage(
                        new PlainText(messageForward.getFix()).plus(chain));
            }

            if (messageForward.getToQq() != null)
            {
                //在消息链前面添加fix
                MessageChain chain = event.getMessage();
                toRobot.getFriend(messageForward.getToQq()).sendMessage(
                        new PlainText(messageForward.getFix()).plus(chain));
            }
        }
    }
}
